package frist50;

import or.T0445.ListNode;
import org.junit.jupiter.api.Test;

public class T0025 {
    public ListNode reverseKGroup(ListNode head, int k) {
        if (k==1)return head;
        ListNode tmp=new ListNode();
        tmp.next=head;
        head=tmp;
        while (true){
            ListNode pathfinder=tmp;
            boolean b=true;
            for (int i = 0; i <k ; i++) {
                pathfinder=pathfinder.next;
                if (pathfinder==null){
                    b=false;
                    break;
                }
            }
            if(!b)break;
            pathfinder=pathfinder.next;
            ListNode tmpNext=tmp.next;
            ListNode left=pathfinder;
            ListNode right=tmp.next;
            for (int i = 0; i <k ; i++) {
                ListNode mod=right;
                right=right.next;
                mod.next=left;
                left=mod;
            }
            tmp.next=left;
            tmp=tmpNext;
        }
        return head.next;
    }

    @Test
    public void test() {
        int [] ints={1,2,3,4,5};
        ListNode node=ListNode.setByArray(ints);
        node=reverseKGroup(node,2);
        node.print();
    }
}
